﻿using System.Text.Encodings.Web;
using Jst.Domain.Shared.Enums;
using Jst.Domain.Shared.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace Jst.Infrastructure.Web.Authentication
{
    public class ApiResponseForAdminHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        public ApiResponseForAdminHandler(
            IOptionsMonitor<AuthenticationSchemeOptions> options,
            ILoggerFactory logger,
            UrlEncoder encoder,
            ISystemClock clock)
            : base(options, logger, encoder, clock) { }

        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
            => throw new NotImplementedException();

        protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Response.ContentType = "application/json";
            var result = ApiResult.Error(ResultCode.UNAUTHORIZED, "很抱歉，您无权访问该接口，请确保已经登录!");
            await Response.WriteAsync(JsonConvert.SerializeObject(result));
        }

        protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
        {
            Response.ContentType = "application/json";
            var result = ApiResult.Error(ResultCode.FORBIDDEN, "很抱歉，您的访问权限等级不够，联系管理员!!");
            await Response.WriteAsync(JsonConvert.SerializeObject(result));
        }
    }
}